package DBLayer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import ModelLayer.Spilsystem;

/**
 * 
 * @author DMAA0213 - Gruppe 2
 *
 */
public class DBSpilsystem implements IFDBSpilsystem {

	private Connection con;

	/**
	 * Constructor for DBSpilsystem objekt, uden parametre.
	 * Her startes DBConnection, hvis denne ikke i forevejen er aktiv. 
	 * @throws SQLException Kaster SQLException hvis der er fejl i connection. 
	 */
	public DBSpilsystem() throws SQLException {
		try {
			con = DBConnection.getInstance().getDBcon();
		}
		catch (SQLException e) {
			throw e;
		}
	}
	
	
	@Override
	public ArrayList<Spilsystem> hentListe() throws SQLException {
		ArrayList<Spilsystem> arrayListSpilsystem = new ArrayList<Spilsystem>();
		
		Spilsystem ss = null;
		String query = "SELECT id, navn, beskrivelse"
				+ " FROM Spilsystem";
		ResultSet result = null;
		try {
			PreparedStatement ps = con.prepareStatement(query);
			result = ps.executeQuery();
			while(result.next()) {
				ss = buildSpilsystem(result);
				arrayListSpilsystem.add(ss);
			}
		} catch (SQLException e) {
			throw e;
		}
		

		return arrayListSpilsystem;
	}	


	
	@Override
	public void indsaet(Spilsystem spilsystem) throws SQLException {
		try {
			String query = "INSERT INTO Spilsystem (id,navn,beskrivelse)"
					+ "values (?,?,?)";
			DBConnection.startTransaction();
			int nextId = GetMax
					.getMaxId("SELECT max(id)+1 FROM Spilsystem");
			spilsystem.setId(nextId);
			PreparedStatement ps = con.prepareStatement(query);
			ps.setInt(1, nextId);
			ps.setString(2, spilsystem.getNavn());
			ps.setString(3, spilsystem.getBeskrivelse());
			ps.executeUpdate();
			DBConnection.commitTransaction();
		} catch (SQLException e) {
			DBConnection.rollbackTransaction();
			throw e;
		}

	}

	
	private Spilsystem buildSpilsystem(ResultSet result) throws SQLException {
		Spilsystem spilObj = new Spilsystem();
		try {
			spilObj.setId(result.getInt("id"));
			spilObj.setNavn(result.getString("navn"));
			spilObj.setBeskrivelse(result.getString("beskrivelse"));

		} catch (SQLException e) {
			System.out.println("error in building the spilsystem object");
			throw e;
		}
		return spilObj;

	}

	
	@Override
	public Spilsystem hent(int id) throws SQLException {
		
		try {
			String query = "SELECT id, navn, beskrivelse"
					+ " FROM Spilsystem WHERE id=?";
			ResultSet result = null;
			PreparedStatement ps = con.prepareStatement(query);
			ps.setInt(1, id);
			result = ps.executeQuery();
			if (result.next()) {
				return buildSpilsystem(result);
			} else {
				return null;
			}
		} catch (SQLException e) {
			throw e;
		}
		
	}
}
